
const md5 = require('md5');
const { loginDao, updateAdminDao } = require('../dao/adminDao');
const jwt = require('jsonwebtoken');
const { ValidationError } = require('../utils/errors');

module.exports.loginService = async function (loginInfo) {
  loginInfo.loginPwd = md5(loginInfo.loginPwd)
  let user = await loginDao(loginInfo)
  if (user && user.dataValues) {
    user = user.dataValues
    // 添加token
    let tokenTime = loginInfo.remember ? parseInt(loginInfo.remember) : parseInt(process.env.TOKEN_TIME)
    let token = jwt.sign({
      id: user.id,
      loginId: user.loginId,
      name: user.name
    }, md5(process.env.JWT_SECRET), { expiresIn: 60 * 60 * 24 * tokenTime })
    return {
      token,
      user
    }
  }
  throw new ValidationError("用户名或密码错误")
}


module.exports.updateAdminService = async function (userInfo) {

  let user = await loginDao({
    loginId: userInfo.loginId,
    loginPwd: md5(userInfo.oldLoginPwd)
  })

  if (user && user.dataValues) {
    let newLoginPwd = md5(userInfo.loginPwd)
    const result = await updateAdminDao({
      loginId: userInfo.loginId,
      name: userInfo.name,
      loginPwd: newLoginPwd
    })
    return {
      loginId: userInfo.loginId,
      name: userInfo.name,
      id: user.id
    }
  } else {
    throw new ValidationError("旧密码不正确")
  }
}